package com.hgk.common.common.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.common.dongqiuhui.apps.comm.tools.BallUtil;
import com.common.nostra13.universalimageloader.core.DisplayImageOptions;
import com.common.nostra13.universalimageloader.core.ImageLoader;
import com.common.nostra13.universalimageloader.core.assist.FailReason;
import com.common.nostra13.universalimageloader.core.assist.ImageSize;
import com.common.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.hgk.common.common.ui.activity.listener.SetCurrentBit;
import com.hgk.common.common.ui.model.PhotosBean;
import com.hgk.common.common.ui.photoview.HackyViewPager;
import com.hgk.common.common.ui.photoview.PhotoView;
import com.hgk.common.common.ui.photoview.PhotoViewAttacher;
import com.hgk.common.common.util.LoadImageDisplayOption;
import com.hgk.wanwan.photo.PhotoProcessConstants;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;

import width.hgk.wanwan.R;

public class ImagePreviewActivity extends BallTitleAcitivty implements SetCurrentBit {
    private static String ISSHOWCONENT="isShowContent";
    private HackyViewPager mViewPager;
    private TextView mTvPosition;
    private Button mBtnGoback;
    private RelativeLayout mRlTitle;
    private RelativeLayout mRlBottom;
    private TextView mTvContent;
    public ArrayList<PhotosBean> mPhotosList;
    private FragmentManager mFragmentManager;
    private ViewAdapter mFAdapter;
    private Bitmap mBit;
    private boolean mIsShowTitle=true;
    private int mPosition=0,photototal_num=0;
    private static boolean mIsDel=false;
    private boolean mIsShowContent = false;//现在主要是判断是否要显示图片保存按钮
    private String mRsid;
    private ImageView mIvArrow;
    private ImageView mIvBack;
    private RelativeLayout mRlSave;
    private DisplayImageOptions mDisplayImageOptions;
    private LinkedHashMap<Integer,ImageChild> mViews=new LinkedHashMap<Integer,ImageChild>();
    private ArrayList<String> mPaths=new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
    }
    private void initData(){
        mPhotosList = (ArrayList<PhotosBean>) getIntent().getSerializableExtra(PhotoProcessConstants.EXTRA_PHOTO_LIST);
        if(mPhotosList!=null&&mPhotosList.size()>0){
        	PhotosBean bean=mPhotosList.get(0);
        	if("-1".equals(bean.getPic_path())){
        		mPhotosList.remove(0);
        	}
        }
        mPosition= getIntent().getIntExtra(PhotoProcessConstants.EXTRA_CURRENT_POSITION, 0);
        mIsDel=getIntent().getBooleanExtra(PhotoProcessConstants.EXTRA_IS_DEL, false);
        mIsShowContent=getIntent().getBooleanExtra(ISSHOWCONENT,false);
    }
    private void initView(){
        mDisplayImageOptions= LoadImageDisplayOption.getDefaultPic(R.drawable.icon);
        getTitleView().setVisibility(View.GONE);
        mIvBack=(ImageView)findViewById(R.id.iv_back);
        mIvBack.setOnClickListener(this);
        mRlSave=(RelativeLayout)findViewById(R.id.rl_save);
        mRlSave.setOnClickListener(this);
        mViewPager = (HackyViewPager)findViewById(R.id.photo_view_pager);
        mTvPosition = (TextView) findViewById(R.id.title_cur_numtv);
        mBtnGoback = (Button) findViewById(R.id.go_back_btn);
        mBtnGoback.setOnClickListener(this);
        mFAdapter=new ViewAdapter(mFragmentManager=getSupportFragmentManager());
        mViewPager.setAdapter(mFAdapter);
        mViewPager.setCurrentItem(mPosition);
        mRlBottom=(RelativeLayout)findViewById(R.id.rl_bottom);
        mRlBottom.setOnClickListener(this);
        mTvContent=(TextView)findViewById(R.id.tv_content);
        if(mIsShowContent){
        	mTvContent.setText(mPhotosList.get(mPosition).getContent());
        	mRsid=mPhotosList.get(mPosition).getRsid();

            mRlBottom.setVisibility(View.VISIBLE);

            mRlSave.setVisibility(View.VISIBLE);
            if(TextUtils.isEmpty(mPhotosList.get(mPosition).getContent())){
                mRlBottom.setVisibility(View.GONE);
            }
        }else{
            mRlBottom.setVisibility(View.GONE);
            mRlSave.setVisibility(View.GONE);
        }
        mIvArrow=(ImageView)findViewById(R.id.img_arrow);
        if("0".equals(mPhotosList.get(mPosition).getRsid())){
            mIvArrow.setVisibility(View.GONE);
        }else{
            mIvArrow.setVisibility(View.VISIBLE);
        }
        photototal_num = mPhotosList.size();
        mTvPosition.setText((mPosition + 1) + "/" + photototal_num);
        initListener();
    }
    @SuppressWarnings("deprecation")
    private void initListener(){
        mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                ImageChild imageChild=mViews.get(arg0);
                imageChild.scrollCallback();
                if("0".equals(mPhotosList.get(arg0).getRsid())){
                    mIvArrow.setVisibility(View.GONE);
                }else{
                    mIvArrow.setVisibility(View.VISIBLE);
                }
                mTvContent.setText(mPhotosList.get(arg0).getContent());
                mRsid=mPhotosList.get(arg0).getRsid();
                mPosition=arg0;
                mTvPosition.setText((arg0 + 1) + "/" + photototal_num);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.go_back_btn:
                finish();
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                break;
            case R.id.iv_photo_select:

                break;
            case R.id.rl_bottom:
                if("0".equals(mPhotosList.get(mPosition).getRsid())){
                    return;
                }
//                CourseDetailActivity.launch(mContext,mPhotosList.get(mPosition).getRsid(),
//                        mPositionhotosList.get(mPosition).getIsrole(), SharedPreferencesUtil.getStringValue(mContext, KeysConstans.USER_ID));
                break;
            case R.id.iv_back:
                if(mIsDel){
                    setResult(true);
                }
                finish();
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                break;
            case R.id.rl_save:
                savePic();
                break;
            default:
                break;
        }
    }
    @Override
    public void setLeftButton(RelativeLayout relativeLayout,Button button) {

    }

    @Override
    public void setRightButton(RelativeLayout relativeLayout,Button button) {
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if(mIsDel){
                    setResult(true);
                }else{
                    finish();
                }
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                break;

            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    public Object getTitleString() {
        return "";
    }

    @Override
    public int getBodyView() {
        return R.layout.photos_activity;
    }

    class ViewAdapter extends FragmentStatePagerAdapter {
        public ViewAdapter(FragmentManager fragmentManager){
            super(fragmentManager);
        }

        public void remove(int position){
            if(mPhotosList!=null&&mPhotosList.size()>=position+1){
                mPhotosList.remove(position);
            }
            if(mViews!=null&&mViews.size()>0){
                mViews.remove(position);
            }
        }
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment fragment=(Fragment)super.instantiateItem(container,position);
            FragmentTransaction ft= mFragmentManager.beginTransaction();
            if(mPhotosList!=null&&mPhotosList.size()>=position+1) {
                ft.replace(container.getId(), fragment, mPhotosList.get(position).getPic_path());
            }
            return fragment;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public int getCount() {
            if(mPhotosList!=null&&mPhotosList.size()>0){
                return mPhotosList.size();
            }
            return 0;
        }

        @Override
        public Fragment getItem(int position) {
            ImageChild imageChild=new ImageChild();
            Bundle bundle=new Bundle();
            bundle.putInt("position", position);
            bundle.putSerializable("photolist", mPhotosList);
            imageChild.setArguments(bundle);
            mViews.put(position, imageChild);
            return imageChild;
        }
    }
    public static class ImageChild extends Fragment {
        private PhotoView pview;
        private RelativeLayout rlview;
        private String mImageUrl;
        private int index=0;
        private ImageLoader mImageLoader;
        private ArrayList<PhotosBean> mPhotolist;
        private ImageSize imgSize = new ImageSize(400, 600);
        private DisplayImageOptions displayImageOptions;
        private ImageView mIvSelect;
        public ImageChild(){
            super();
            mImageLoader = ImageLoader.getInstance();
            displayImageOptions = LoadImageDisplayOption
                    .getDefaultPicForDrable(R.drawable.icon);
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.iamge_fragment,null);
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            Bundle bundle=getArguments();
            this.index=bundle.getInt("position");
            this.mPhotolist=(ArrayList<PhotosBean>) bundle.getSerializable("photolist");
            rlview = (RelativeLayout)getView().findViewById(R.id.rl_photoview);
            pview = (PhotoView) getView().findViewById(
                    R.id.iv_photo);
            mIvSelect=(ImageView)getView().findViewById(R.id.iv_photo_select);
            if(mIsDel){
                mIvSelect.setVisibility(View.VISIBLE);
            }else{
                mIvSelect.setVisibility(View.GONE);
            }
            mIvSelect.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ((ImagePreviewActivity)getActivity()).removeItem(index);
                }
            });
            final ProgressBar pb = (ProgressBar) getView()
                    .findViewById(R.id.pb);
            pview.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                @Override
                public void onPhotoTap(View view, float x, float y) {
//                    ((ImagePreviewActivity) getActivity()).setTitleIsVisiBle();
                	((ImagePreviewActivity) getActivity()).finish();
                	((ImagePreviewActivity) getActivity()).overridePendingTransition(0, R.anim.activity_fade_out);
                }
            });
            if(mPhotolist!=null&&mPhotolist.size()>=index+1){
                if(!TextUtils.isEmpty(mPhotolist.get(index).getPic_path())){
                    mImageUrl=mPhotolist.get(index).getPic_path();
                }
            }

            if(mImageUrl!=null && !TextUtils.isEmpty(mImageUrl) && pview!=null){
                try {
                    mImageLoader.loadImage(BallUtil.getPhotoPath(mImageUrl), imgSize, displayImageOptions,
                            new ImageLoadingListener() {

                                @Override
                                public void onLoadingStarted(String imageUri, View view) {
                                    pb.setVisibility(View.VISIBLE);
                                }

                                @Override
                                public void onLoadingFailed(String imageUri, View view,
                                                            FailReason failReason) {
                                    try {
                                        pb.setVisibility(View.GONE);
                                        pview.setImageResource(R.drawable.icon);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onLoadingComplete(String imageUri,
                                                              View view, Bitmap loadedImage) {
                                    try {
                                        int w = loadedImage.getWidth();
                                        int h = loadedImage.getHeight();
                                        RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams)pview.getLayoutParams();
                                        if (w<h){
                                            rlp.width=BallUtil.getScreenWidth(((ImagePreviewActivity)getActivity()));
                                            rlp.height=rlp.width*h/w;
                                            rlview.getLayoutParams().width = BallUtil.getScreenWidth(((ImagePreviewActivity)getActivity()));
                                            rlview.getLayoutParams().height = rlp.width*h/w;
                                        }
//                                        pview.setScale(1,true);
                                        pb.setVisibility(View.GONE);
                                        ((ImagePreviewActivity)getActivity()).setBit(loadedImage);
                                        pview.setImageBitmap(loadedImage);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onLoadingCancelled(String imageUri, View view) {
                                }
                            });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        public void scrollCallback(){
            if(pview!=null){
                pview.resetMatrix();
            }
        }
    }
    @Override
    public void setBit(Bitmap mbit) {
        mBit = mbit;
    }
    @Override
    public void setTitleIsVisiBle() {
//		if (mIsShowTitle) {
//        	mIsShowTitle = false;
//            mRlTitle.setVisibility(View.GONE);
//        } else {
//        	mIsShowTitle = true;
//            mRlTitle.setVisibility(View.VISIBLE);
//        }
    }
    @Override
    public void removeItem(int position) {
        mFAdapter.remove(position);
        mFAdapter.notifyDataSetChanged();
        photototal_num--;
        mTvPosition.setText((mViewPager.getCurrentItem()+1) + "/" + photototal_num);
        if(mFAdapter.getCount()==0){
            setResult(false);
        }
    }
    //返回值提取出一个返回调用函数
    private void setResult(boolean isDel){
        if(isDel){
            for (int i = 0; i < mPhotosList.size(); i++) {
                mPaths.add(mPhotosList.get(i).getPic_path());
            }
        }
        Intent intent=new Intent();
        Bundle bundle=new Bundle();
        bundle.putStringArrayList(PhotoProcessConstants.EXTRA_PHOTO_LIST, mPaths);
        intent.putExtra("bundle", bundle);
        setResult(RESULT_OK, intent);
        finish();
    }

    public static void launch(Context context,int position,ArrayList<String> paths,ArrayList<PhotosBean> photos,boolean isDel){
        if(photos==null)
            photos=new ArrayList<PhotosBean>();
        if(paths!=null&&paths.size()>0){
            for(int i=0;i<paths.size();i++){
                PhotosBean bean = new PhotosBean();
                bean.setPic_path(paths.get(i));
                photos.add(bean);
            }
        }
        Intent intent=new Intent(context,ImagePreviewActivity.class);
        intent.putExtra(PhotoProcessConstants.EXTRA_CURRENT_POSITION, position);
        intent.putExtra(PhotoProcessConstants.EXTRA_IS_DEL, isDel);
        intent.putParcelableArrayListExtra(PhotoProcessConstants.EXTRA_PHOTO_LIST, (ArrayList<? extends Parcelable>) photos);
        if(isDel){
        	((Activity)context).startActivityForResult(intent, PhotoProcessConstants.DEL_BIG_PHOTO_CODE);
        }else{
        	context.startActivity(intent);
        }
    }

   /* public static void launch(Context context,int position,List<PhotosBean> photoslist,boolean isDel){
          if(photoslist!=null&&photoslist.size()>0){
              Intent intent=new Intent(context,ImagePreviewActivity.class);
              intent.putExtra(PhotoProcessConstants.EXTRA_CURRENT_POSITION, position);
              intent.putExtra(PhotoProcessConstants.EXTRA_IS_DEL, isDel);
              intent.putParcelableArrayListExtra(PhotoProcessConstants.EXTRA_PHOTO_LIST, (ArrayList<? extends Parcelable>) photoslist);
              if(isDel){
                  ((Activity)context).startActivityForResult(intent, PhotoProcessConstants.DEL_BIG_PHOTO_CODE);
              }else{
                  context.startActivity(intent);
                  ((Activity)context).overridePendingTransition(R.anim.activity_fade_in,0);
              }
          }
    }*/

    public static void launch(Context context,int position,List<PhotosBean> photoslist,boolean isDel,boolean isShowContent){
        if(photoslist!=null&&photoslist.size()>0){
            Intent intent=new Intent(context,ImagePreviewActivity.class);
            intent.putExtra(PhotoProcessConstants.EXTRA_CURRENT_POSITION, position);
            intent.putExtra(PhotoProcessConstants.EXTRA_IS_DEL, isDel);
            intent.putExtra(ISSHOWCONENT,isShowContent);
            intent.putParcelableArrayListExtra(PhotoProcessConstants.EXTRA_PHOTO_LIST, (ArrayList<? extends Parcelable>) photoslist);
            if(isDel){
                ((Activity)context).startActivityForResult(intent, PhotoProcessConstants.DEL_BIG_PHOTO_CODE);
            }else{
                context.startActivity(intent);
            }
        }

    }

    private void savePic(){
        ImageLoader.getInstance().loadImage(BallUtil.getPhotoPath(mPhotosList.get(mPosition).getPic_path()), mDisplayImageOptions,
                new ImageLoadingListener() {

                    @Override
                    public void onLoadingStarted(String imageUri, View view) {
                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view,
                                                FailReason failReason) {
                        Toast.makeText(mContext, "保存失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onLoadingComplete(String imageUri,
                                                  View view, Bitmap loadedImage) {
                        writeBitmapForFile(loadedImage);
                    }

                    @Override
                    public void onLoadingCancelled(String imageUri,
                                                   View view) {
                    }
                });
    }
    private void writeBitmapForFile(Bitmap bmp) {
        // 压缩
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            String fName = "";
            String path  = Environment.getExternalStorageDirectory().getPath()
                    + "/zaiwan";
            // 存文件
            File f = new File(path);
            if (!f.exists()) {
                f.mkdirs();
            }
            fName = path + "/" + getPhotoFilename(new Date());
            FileOutputStream tmpFox = new FileOutputStream(fName);
            tmpFox.write(baos.toByteArray());
            tmpFox.close();
            Toast.makeText(this, "保存成功 :" + fName, Toast.LENGTH_SHORT).show();
            Intent scanIntent = new Intent(
                    Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            scanIntent.setData(Uri.fromFile(new File(fName)));
            sendBroadcast(scanIntent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
            return;
        }
    }
    /**
     * 读取图片文件名
     *
     * @param date
     * @return
     */
    private String getPhotoFilename(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddKms",
                Locale.CHINA);
        return dateFormat.format(date) + ".jpg";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
